<template>
  <div class="film-list">

    <el-dialog
      title="电影信息修改"
      :visible.sync="dialog1"
      width="60%">

      <el-form ref="form1" style="padding: 20px" :model="form" :data="form" label-width="90px" :rules="rules">

        <el-form-item label="电影封面">
          <el-upload
            class="upload-demo"
            drag
            accept=".png,.jpg"
            :limit="1"
            :headers="header"
            :action="uploadAction"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :on-exceed="handleExceed"
            multiple>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过20MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="电影封面">
          <div v-text="url"></div>
        </el-form-item>

        <el-form-item label="电影名称" prop="name" :required="form.name?false:true">
          <el-input v-model="form.name"></el-input>
        </el-form-item>

        <el-form-item label="上映地区">
          <el-select v-model="form.region" placeholder="请选择上映区域">
            <el-option label="中国大陆" value="中国大陆"></el-option>
            <el-option label="中国香港" value="中国香港"></el-option>
            <el-option label="中国台湾" value="中国台湾"></el-option>
            <el-option label="日本" value="日本"></el-option>
            <el-option label="美国" value="美国"></el-option>
            <el-option label="韩国" value="韩国"></el-option>
            <el-option label="英国" value="英国"></el-option>
            <el-option label="法国" value="法国"></el-option>
            <el-option label="印度" value="印度"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="放映类型">
          <el-select v-model="form.showType" placeholder="请选择放映类型">
            <el-option label="2D 放映" value="2D放映"></el-option>
            <el-option label="3D 放映" value="3D放映"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="全片时长" prop="duration">
          <el-input-number v-model="form.duration" :min="10" :max="550"></el-input-number>
          <span>  /min</span>
        </el-form-item>

        <el-form-item label="上映时间" prop="releaseTime">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="form.releaseTime"
                            style="width: 100%;"></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item label="即时上架">
          <el-switch v-model="form.status"></el-switch>
        </el-form-item>

        <el-form-item label="电影类型">
          <el-radio-group v-model="form.type">
            <el-radio style="padding-bottom: 20px" label="爱情"></el-radio>
            <el-radio label="喜剧"></el-radio>
            <el-radio label="科幻"></el-radio>
            <el-radio label="动画"></el-radio>
            <el-radio label="剧情"></el-radio>
            <el-radio style="padding-bottom: 20px" label="恐怖"></el-radio>
            <el-radio label="悬疑"></el-radio>
            <el-radio label="冒险"></el-radio>
            <el-radio label="动作"></el-radio>
            <el-radio style="padding-bottom: 20px" label="犯罪"></el-radio>
            <el-radio label="历史"></el-radio>
            <el-radio label="古装"></el-radio>
            <el-radio label="战争"></el-radio>
            <el-radio label="纪录片"></el-radio>
            <el-radio style="padding-bottom: 20px" label="家庭"></el-radio>
            <el-radio label="传记"></el-radio>
            <el-radio label="武侠"></el-radio>
            <el-radio label="儿童"></el-radio>
            <el-radio label="短片"></el-radio>
            <el-radio label="其他"></el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="内容简介" prop="introduction" :required="form.introduction?false:true">
          <el-input rows="8" type="textarea" v-model="form.introduction"></el-input>
        </el-form-item>

      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog1 = false">取 消</el-button>
        <el-button type="primary" @click="submitUpdate()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="新增电影排片"
      :visible.sync="dialog2"
      width="50%"
      @close="handleClose">

      <el-form ref="form" :model="arrangement" label-width="90px" :rules="rules">

        <el-form-item label="电影名称">
          <el-input :disabled="true" v-model="arrangement.name"></el-input>
        </el-form-item>

        <el-form-item label="开放座位" prop="seatNumber">
          <el-input-number v-model="arrangement.seatNumber" :min="10" :max="100"></el-input-number>
        </el-form-item>

        <el-form-item label="放映类型">
          <el-select v-model="arrangement.type" placeholder="请选择放映类型" :disabled="true">
            <el-option label="2D 放映" value="2D放映"></el-option>
            <el-option label="3D 放映" value="3D放映"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item style="width: 500px" label="放映日期" prop="date">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="选择日期" v-model="arrangement.date"
                            value-format="yyyy-MM-dd" style="width: 100%;" :picker-options="pickerOptionsDate"></el-date-picker>
          </el-col>
        </el-form-item>

        <el-form-item style="width: 500px" label="放映时间">
          <el-col :span="11">
            <el-form-item prop="startTime">
             <el-time-picker placeholder="开始时间" value-format="HH:mm:ss" v-model="arrangement.startTime"
                            style="width: 100%;" :picker-options="{selectableRange: `00:00:00 - ${arrangement.endTime ? arrangement.endTime : '23:59:59'}`}"></el-time-picker>
            </el-form-item>
          </el-col>
          <el-col style="text-align: center" class="line" :span="2">-</el-col>
          <el-col :span="11">
            <el-form-item prop="endTime">
              <el-time-picker placeholder="结束时间" value-format="HH:mm:ss" v-model="arrangement.endTime"
                            style="width: 100%;" :picker-options="{selectableRange: `${arrangement.startTime ? arrangement.startTime : '00:00:00'} - 23:59:59`}"></el-time-picker>
            </el-form-item>
          </el-col>
        </el-form-item>

        <el-form-item label="电影票价" prop="price">
          <el-input-number v-model="arrangement.price" :precision="2" :step="0.1"
                           :min="9.99" :max="999.99"></el-input-number>
        </el-form-item>

<!--        <el-form-item label="排片人">-->
<!--          <el-input type="textarea" v-model="arrangement.founder"></el-input>-->
<!--        </el-form-item>-->
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog2 = false">取 消</el-button>
        <el-button type="primary" @click="submitArrange()">确 定</el-button>
      </span>
    </el-dialog>

    <el-table
      v-loading="tableLoading"
      :data="filmList.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%"
      height="630"
      :default-sort = "{prop: 'date', order: 'descending'}"
    >

      <el-table-column label="电影名" prop="name">
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 145px"
            :src="scope.row.cover">
          </el-image>
          <el-tooltip
            v-model="scope.row.showTooltip"
            effect="dark"
            :disabled="!scope.row.showTooltip"
            :content="scope.row.name"
            placement="top"
            :open-delay="100"
          >
           <div
             style="font-size: 10px;padding-top: 5px;padding-left: 3px;"
             @mouseover="isShowTooltip($event, scope.row)"
             >
             {{scope.row.name | ellipsis}}
           </div>
          </el-tooltip>
        </template>
      </el-table-column>

      <el-table-column
        label="上映时间"
        :formatter="formatter"
        prop="releaseTime"
        sortable>
      </el-table-column>

      <el-table-column
        label="类型"
        prop="type">
      </el-table-column>

      <el-table-column label="上架状态" prop="status" sortable>
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status === true" type="success" disable-transitions>上架</el-tag>
          <el-tag v-if="scope.row.status === false" type="warning" disable-transitions>下架</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="放映类型" prop="showType" sortable>
        <template slot-scope="scope">
          <el-tag effect="dark" v-if="scope.row.showType === '2D放映'" type="success" disable-transitions>2D 放映</el-tag>
          <el-tag effect="dark" v-if="scope.row.showType === '3D放映'" type="primary" disable-transitions>3D 放映</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="地区"
        prop="region">
      </el-table-column>

      <el-table-column label="电影时长">
        <template slot-scope="scope">
          <el-tag size="medium" effect="plain">{{ scope.row.duration }} 分钟</el-tag>
        </template>
      </el-table-column>

      <el-table-column width="260" align="right">
<!--        <template slot="header" slot-scope="scope">-->
<!--          <el-input-->
<!--            v-model="search"-->
<!--            size="mini"-->
<!--            placeholder="输入关键字搜索"/>-->
<!--        </template>-->
        <template slot="header" slot-scope="scope">
          <el-form>
            <el-input v-model="name"  size="mini" placeholder="请输入电影名称进行搜索" style="width:180px;float: left;" />
            <el-button type="primary" size="mini" @click="searchByName">查询</el-button>
          </el-form>
        </template>
        <template style="white-space: nowrap" slot-scope="scope">
          <el-button
            size="mini"
            icon="el-icon-edit"
            type="primary"
            @click="handleEdit(scope.$index, scope.row)">修改
          </el-button>
          <el-button
            size="mini"
            icon="el-icon-circle-plus"
            type="success"
            @click="handleArrange(scope.$index, scope.row)">排片
          </el-button>
          <el-popconfirm
            confirm-button-text='确定'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            @confirm=handleDelete(scope.$index,scope.row)
            title=" 确定要删除此电影吗? "
          >
            <el-button
              style="margin-left: 8px"
              size="mini"
              icon="el-icon-delete"
              type="danger"
              slot="reference">删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>

    </el-table>

    <div style="text-align:center;">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.params.page"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="this.params.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      >
      </el-pagination>
    </div>

  </div>
</template>

<script>
  import {ListAllFilm, DeleteById, UpdateFilm, AddArrangement, findFilmById} from "@/api/film";
  import config from "@/config";
  import { formatDate } from "@/utils/formatter";


  export default {
    inject:['reload'],
    data() {
      const isEmpty = (rule, value, callback) => {
        if (value == '') {
          callback(new Error(rule.message))
        } else {
          callback()
        }
      };
      return {
        rules: {
          seatNumber: [
            { required: true, message: '请规定座位数量！', trigger: 'blur' }
          ],
          date: [
            { required: true, message: '放映日期不能为空！', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '放映开始时间不能为空！', trigger: 'blur' }
          ],
          endTime: [
            { required: true, message: '放映结束时间不能为空！', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '电影票价不能为空！', trigger: 'blur' }
          ],
          name: [
            {  validator: isEmpty, message: '电影名称不能为空！', trigger: ['blur','change'] }
          ],
          duration: [
            { required: true, message: '全片时长不能为空！', trigger:  'change' }
          ],
          releaseTime: [
            { required: true, message: '上映时间不能为空！', trigger: 'blur' }
          ],
          introduction: [
            { validator: isEmpty, message: '内容简介不能为空！', trigger: ['blur','change'] }
          ],
        },
        header: {
          "Authorization": localStorage.getItem("token")
        },
        uploadAction: config.API_URL + '/upload',
        url: '',
        tableLoading: false,
        form: {
          cover: 'null',
          name: '',
          region: '',
          releaseTime: '',
          duration: 120,
          introduction: '',
          type: '',
          status: true,
        },
        arrangement: {
          name: '',
          fid: '',
          seatNumber: 40,
          price: 30.50,
          date: '',
          startTime: '',
          endTime: '',
          founder: '',
          type: '2D放映',
          releaseTime: '',
        },
        pickerOptionsDate: {
          disabledDate: (time) => {
            if (this.arrangement.releaseTime) {
              return  time.getTime() < new Date(this.arrangement.releaseTime).getTime();
            } else {
              return time.getTime() < new Date(new Date().toLocaleDateString()).getTime();
            }
          }
        },
        filmList: [],
        searchList:[],
        search: '',
        dialog1: false,
        dialog2: false,
        total: 0,
        params: {
          page: 1,
          limit: 10,
        },
        name: '',
      }
    },

    filters:{
      ellipsis(value){
        if (!value) return '';
        if (value.length > 8) {
          return value.slice(0,8) + '...'
        }
        return value
      }
    },

    mounted() {
      // this.tableLoading = true;
      // ListAllFilm().then(res => {
      //   setTimeout(() => {
      //     this.filmList = res.data;
      //     this.tableLoading = false;
      //   }, 200)
      // })
      this.listFilmByPage();
    },

    methods: {

      submitUpdate() {
        this.$refs.form1.validate((valid) => {
          if (valid) {
            this.form.cover = this.url;
            UpdateFilm(this.form).then(res => {
              if (res.success) {
                // this.reload();
                this.dialog1 = false;
                this.$message({
                  message: '电影《' + this.form.name + '》修改成功！',
                  type: 'success',
                });
                this.listFilmByPage();
              }
            })
          }
        });
      },

      submitArrange() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            // 调用接口保存
            AddArrangement(this.arrangement).then(res => {
              this.dialog2 = false;
              if (res.success) {
                this.$message({
                  message: '电影排片《' + this.arrangement.name + '》新增成功！',
                  type: 'success',
                });
              }
            })
          }
        });
      },

      handleEdit(index, row) {
        this.dialog1 = true;
        this.url = row.cover;
        // console.log(this.form)
        findFilmById(row.id).then(res => {
          setTimeout(() => {
            this.form = res.data;
          },10)
        })
      },

      handleArrange(index, row) {
        this.dialog2 = true;
        this.arrangement.name = row.name
        this.arrangement.fid = row.id
        this.arrangement.type = row.showType
        this.arrangement.releaseTime = row.releaseTime
      },

      handleDelete(index, row) {
        DeleteById(row.id).then(res => {
          if (res.success) {
            this.filmList.splice(index, 1)
            this.reload();
            this.$message({
              message: '电影《' + row.name + '》删除成功！',
              type: 'success'
            });
          }
        })
      },

      handleUploadSuccess(res) {
        this.url = res;
      },

      beforeUpload(file) {
        let isLt10M = file.size / 1024 / 1024 / 20 < 1
        if(!isLt10M) {
          this.$message.error("上传文件大小不能超过 20MB!")
        }
        return isLt10M;
      },

      handleExceed(files, fileList) {
        this.$message.warning('超出1个文件，请先删除当前文件，再重新上传')
        return false
      },

      handleClose(){
        this.$refs.form.resetFields();
      },

      formatter(row,column) {
        return formatDate('YYYY-mm-dd',row[column.property]);
      },

      isShowTooltip(obj, row) {
        if (row.name.length > 8) {
          row.showTooltip = true
        } else {
          row.showTooltip = false
        }
      },

      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.params.limit = val;
        this.listFilmByPage();
      },

      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.params.page = val;
        this.listFilmByPage();
      },

      searchByName() {
        let params = {
          page: this.params.page,
          limit: this.params.limit,
          name: this.name
        };
        this.$axios({
          method: 'get',
          url: config.API_URL + "/film/like",
          params: params,
          headers: {
            "Authorization": localStorage.getItem("token")
          },
        })
          .then((res) => {
              console.log(res.data.data)
            this.filmList = res.data.data.list;
            this.total = res.data.data.total;
          })
        .catch((error) => {
          let errMsg = error.response.data.msg;
          this.$message.error(errMsg)
        })
      },

      listFilmByPage:function(){
        this.$axios({
          method: 'get',
          url: config.API_URL + "/film/page?page=" + this.params.page + "&limit=" + this.params.limit,
          headers: {
            "Authorization": localStorage.getItem("token")
          },
        })
          .then((res) => {
            console.log(res.data);
            this.filmList = res.data.data.list;
            this.total = res.data.data.total;
          });
      },

    },
  }
</script>

<style scoped>
  .film-list {
    height: 500px;
  }
</style>
